package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.ScheduleApplication;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.crypto.modes.kgcm.Tables4kKGCMMultiplier_128;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.awt.image.CropImageFilter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {


    @Autowired
    private CacheService cacheService;


    /**
     * 添加延迟任务
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        boolean success  = addTaskToDb(task);
        //2.添加任务到redis中
        addTaskToCache(task);

        return 1;
    }

    /**
     * 网路不通，使用延迟任务重试，达到阈值后，删除任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {

        boolean flag = false;
        //1.删除任务，更新任务日志
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);

        //2.删除redis 的数据
        if(task != null){
            removeTaskFormCache(task);
            flag = true;
        }


        return flag;
    }

    /**
     * 删除redis中的数据
     * @param task
     */
    private void removeTaskFormCache(Task task) {

        if(task != null){

            String key = task.getTaskType() + "_" + task.getPriority();
            if(task.getExecuteTime() <= System.currentTimeMillis()){
                cacheService.lRemove(ScheduleConstants.TOPIC + key,0,JSON.toJSONString(task));
            } else {
                cacheService.zRemove(ScheduleConstants.FUTURE,JSON.toJSONString(task));
            }
        }
    }

    /**
     * 删除任务，更细任务日志
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status){

        Task task = null;

        try {
            // 删除任务
            taskinfoMapper.deleteById(taskId);
            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        } catch (Exception e){
            log.error("task cancel exception taskId = {}",taskId);
        }

        return task;
    }

    /**
     * 添加任务到redis中
     * @param task
     */
    private void addTaskToCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        //获取未来5分钟的时间 毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextTimeInMillis = calendar.getTimeInMillis();

        //2.1如果任务执行时间小于等于当前时间，存入到list（当前任务）中
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }

        //2.2如果任务执行时间大于当前时间&&小于等于预设时间（5分钟），存入到zset（未来任务）中
        else if (task.getExecuteTime() <= nextTimeInMillis){
            cacheService.zAdd(ScheduleConstants.FUTURE + key,JSON.toJSONString(task),task.getExecuteTime());
        }


    }


    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flag = false;

        try {

            //1.添加任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //补充taskID
            task.setTaskId(taskinfo.getTaskId());

            //2.添加任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task,taskinfoLogs);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogs.setVersion(1);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag  = true;

        } catch (Exception e){
            e.printStackTrace();
        }


        return flag;
    }

    /**
     * 按类型和优先级拉取数据
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task pull(int type, int priority) {

        String key = type + "_" + priority;

        Task task = null;
        try {

            //拉取redis中的数据 pop
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            task = JSON.parseObject(task_json, Task.class);

            //修改数据库
            updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);

        }catch (Exception e){
            e.printStackTrace();
            log.error("redis pull exception");
        }


        return task;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){

        //加锁 --- > set key value nx ex
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if(StringUtils.isNotBlank(token)){

            log.info("未来数据定时刷新 -- 定时任务");

            //1.获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                //获取当前数据的key topic
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

                //2.根据key和分值获取数据集合
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                //同步数据
                if(!tasks.isEmpty()){
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                    log.info("成功的将"+futureKey+"刷新到"+topicKey);
                }

            }
        }
        }

    /**
     * 数据库定时刷新到redis中
     */
    @PostConstruct  //该服务启动时就进行数据库的刷新
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //1.清空redis中的数据
        clearCache();

        //2.查询符合条件的任务，小于未来五分钟的任务
        //获取未来五分钟的毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        //3.把任务添加到redis中
        if (!taskinfoList.isEmpty() && taskinfoList.size()>0) {
            try {

                for (Taskinfo taskinfo : taskinfoList) {
                    Task task = new Task();
                    BeanUtils.copyProperties(taskinfo, task);
                    task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                    addTaskToCache(task);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        log.info("数据库的任务同步到redis");

    }

    public void clearCache(){
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC);

        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }


}
